<template>
  <div class="recommend">
    <!-- 主页轮播图 -->
    <Swiper></Swiper>
    <!-- 主页轮播图 -->
    <BorderTitle>推荐歌单</BorderTitle>
    <ul class="songlist" v-if="songList.length > 0">
      <ListItem v-for="sl in songList" :key="sl.id" :item="sl"></ListItem>
    </ul>
    <Loading v-if="songList.length == 0"></Loading>

    <BorderTitle>最新音乐</BorderTitle>
    <ul class="newsong" v-if="songList.length > 0">
      <li v-for="s in newSong" :key="s.id">
        <SongItem :item="s" @add-list="addMusicList(newSong)"></SongItem>
      </li>
    </ul>
    <Loading v-if="newSong.length == 0"></Loading>
  </div>
</template>
<script>
import BorderTitle from "@/components/BorderTitle";
import ListItem from "@/components/ListItem";
import SongItem from "@/components/SongItem";
import Loading from "@/components/Loading";
import Swiper from "@/components/Swiper"
export default {
  name: "recommend",
  components: {
    BorderTitle,
    ListItem,
    SongItem,
    Loading,
    Swiper
  },
  data() {
    return {
      songList: [],
      newSong: [],
    };
  },
  methods: {
    addMusicList(newSong) {
      //把当前最新歌曲列表全部加入播放清单
      // this.$root.musicStore.musicList=this.$root.musicStore.musicList.concat(newSong)
      //发现存在id重复导致报错的问题，所以要去重
      let newArr = this.$root.musicStore.musicList; //原来的播放列表
      newSong.map((d) => {
        //处理newSong里面每一条音乐
        let find = false; //标志是否找到相同的ID
        for (let n of newArr) {
          if (n.id == d.id) {
            //假如找到了相同的ID
            find = true;
            break; //假如找到了，break跳出这个for循环
          }
        }
        if (!find) {
          //如果当前音乐在newArr里面没有找到的话，就加入newArr
          newArr.push(d);
        }
      });
      this.$root.musicStore.musicList = newArr;
    },
  },
  created() {
    //获取推荐歌单
    this.$http
      .get("/personalized?limit=9")
      .then((data) => {
        this.songList = data.data.result;
      })
      .catch((err) => {
        console.log(err);
      });
    //获取最新音乐
    this.$http
      .get("/personalized/newsong?limit=20")
      .then((data) => {
        this.newSong = data.data.result;
      })
      .catch((err) => {
        console.log(err);
      });
  },
};
</script>
<style lang="less" scoped>
.recommend {
  background: rgb(15, 15, 15);
  .songlist {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    li {
      width: 33%;
    }
  }
  .newsong {
    padding: 10px 10px;
  }
}
</style>
